<script setup lang="ts">
import { useGuessList } from '@/composables/index'
import { getHomeBannerApi, getHomeCategoryApi, getHomeHotApi } from '@/services/home' // 引用定义好的接口api
import type { BannerItem, CategoryItem, HotItem } from '@/types/home' // 引用定义的ts类型

import CustomNavbar from '@/pages/index/components/CustomNavbar.vue'
import CategoryPanel from '@/pages/index/components/CategoryPanel.vue'
import HotPanel from '@/pages/index/components/HotPanel.vue'
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue'

import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

const bannerList = ref<BannerItem[]>([]) // 定义bannerList变量接受轮播图的数据并定义类型
// 获取轮播图数据
const getHomeBannerData = async () => {
  const res = await getHomeBannerApi()
  bannerList.value = res.result
}

// 获取分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryApi()
  categoryList.value = res.result
}
// 获取热门推荐数据
const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotApi()
  hotList.value = res.result
}

// 从封装的组合式函数中解构猜你喜欢组件实例和滚动触底获取分页数据方法
const { guessRef, onScrollTolower } = useGuessList()

// 是否开启下拉刷新
const isTriggered = ref(false)

// 下拉刷新的方法（refresher-enabled 属性 开启滚动组件的下拉刷新）
const onRefresherrefresh = async () => {
  isTriggered.value = true // 开启下拉动画
  guessRef.value?.resetData() // 调用子组件重置方法
  // 所有异步操作都返回结果时，关闭动画。（Promise.al：同时发起多个异步）
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore(),
  ])
  isTriggered.value = false // 关闭下拉动画
}

// 加载中标记
const isLoading = ref(false)

onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <scroll-view
    scroll-y
    class="scroll-view"
    refresher-enabled
    @scrolltolower="onScrollTolower"
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 自定义轮播图 全局组件-->
      <XtxSwiper :list="bannerList" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 全局组件-->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
